﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Text;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Openfree.Framework.DataAccess;
using ICSS.Office.Word;
using System.Collections.Generic;
using ICSS.Office.Core;

public partial class TaskAcceptDispatch : PMSBase
{ 
    protected void Page_Load(object sender, EventArgs e)
    {
        this.TableName = "PMS_TaskLX";
        this.Key = "TaskID";
        if (!IsPostBack)
        {
            TabsMenuItem[] listItem = new TabsMenuItem[8];
            listItem[0] = new TabsMenuItem();
            listItem[0].Text = "受理信息";
            listItem[0].ClientID = pnlTaskInfo.ClientID;
            listItem[0].OnClientClick = "$('btnSelect').style.display='none';$('btnSave').style.display=''";
            listItem[1] = new TabsMenuItem();
            listItem[1].Text = "任务派发";
            listItem[1].ClientID = pnlTaskPerson.ClientID;
            listItem[1].OnClientClick = "$('btnSelect').style.display='';$('btnSave').style.display=''";
            tabsMenu.TabsMenuItemArray = listItem;
            tabsMenu.CssClass = "tabsMenuA";

            string cmdText = @"select a.*,case when B.status is null then '"+PMSGoodsState.NotOut+@"' else B.status end ReqStatus, (select Username from T_User where UserID=a.UserID) Username from PMS_TaskLX a 
                    left join IC_Requisition B on B.TaskID=a.TaskID where a.TaskState = '"+PMSTaskState.Running+"' order by CreateDate desc";
            //默认受理中
            cmdText = @"select '' as TaskCode,C.TaskID as TaskItemID,C.TaskID,'' as SNYear,'' as SNGroup,'' as SNTask,'' as SNProject,'' as SNDispatch,C.TaskState,'' as GroupName,C.Guest,C.Phone,C.Location,C.CreateDate,case when B.status is null then '" + PMSGoodsState.NotOut + @"' else B.status end ReqStatus, (select Username from T_User where UserID=C.UserID) Username from PMS_TaskLX C left join IC_Requisition B on B.TaskID=C.TaskID where C.TaskState = '" + PMSTaskState.Running + "'";

//            cmdText += @" union all select a.TaskItemID,a.TaskID,a.SNYear,a.SNGroup,a.SNTask,a.SNProject,a.SNDispatch,a.TaskState,D.CodeName as GroupName,C.Guest,C.Phone,C.Location,C.CreateDate,case when B.status is null then '" + PMSGoodsState.NotOut + @"' else B.status end ReqStatus, (select Username from T_User where UserID=C.UserID) Username from PMS_TaskItem a 
//                   left join IC_Requisition B on B.TaskID=a.TaskID left join PMS_TaskLX C on c.TaskID = a.TaskID left join T_CodeConfig D on D.CodeValue=a.SNGroup AND D.Category = '" + PMSCodeCategory.PMS_BMZB + "'  where 1=1  order by C.CreateDate desc";
           
            FillGirdView(0, cmdText); 
            if (!string.IsNullOrEmpty(Request["TaskID"]))
            {
                this.btnEdit_Click(sender, e);
            }
        }
        else
        {
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
 
        }
    } 
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string cmdText = "";
        if (S_TaskState.SelectedValue == "" + PMSTaskState.Running)
        {
            cmdText = @"select ''as TaskCode,C.TaskID TaskItemID,C.TaskID,'' as SNYear,'' as SNGroup,'' as SNTask,'' as SNProject,'' as SNDispatch,C.TaskState,'' as GroupName,C.Guest,C.Phone,C.Location,C.CreateDate,case when B.status is null then '" + PMSGoodsState.NotOut + @"' else B.status end ReqStatus, (select Username from T_User where UserID=C.UserID) Username from PMS_TaskLX C left join IC_Requisition B on B.TaskID=C.TaskID where C.TaskState = '" + PMSTaskState.Running + "' ";
        }
        else if (S_TaskState.SelectedValue == ""+ PMSTaskState.Dispatch)
        {
            cmdText = @"select a.TaskCode,a.TaskItemID,a.TaskID,a.SNYear,a.SNGroup,a.SNTask,a.SNProject,a.SNDispatch,a.TaskState,D.CodeName as GroupName,C.Guest,C.Phone,C.Location,C.CreateDate,case when B.status is null then '" + PMSGoodsState.NotOut + @"' else B.status end ReqStatus, (select Username from T_User where UserID=C.UserID) Username from PMS_TaskItem a 
                   left join IC_Requisition B on B.TaskID=a.TaskItemID inner join PMS_TaskLX C on c.TaskID = a.TaskID left join T_CodeConfig D on D.CodeValue=a.SNGroup AND D.Category = '" + PMSCodeCategory.PMS_BMZB + "' where 1=1 ";

        }   
        StringBuilder sql = new StringBuilder(cmdText);

        if (!string.IsNullOrEmpty(S_Guest.Text.Trim()))
        {
            sql.Append(" AND C.Guest like '%").Append(S_Guest.Text.Trim()).Append("%'");
        }
        if (!string.IsNullOrEmpty(S_Phone.Text.Trim()))
        {
            sql.Append(" AND C.Phone = '").Append(S_Phone.Text.Trim()).Append("'");
        }
        if(S_TaskState.SelectedValue == ""+PMSTaskState.Dispatch){

            if (!string.IsNullOrEmpty(S_TaskCode.Text.Trim()))
            {
                sql.Append(" AND a.TaskCode = '").Append(S_TaskCode.Text.Trim()).Append("'");
            }
            if (!string.IsNullOrEmpty(S_TaskState.SelectedValue))
            {
                sql.Append(" AND a.TaskState = '").Append(S_TaskState.SelectedValue).Append("'");
            }
        }
        sql.Append(" order by C.CreateDate desc");
        FillGirdView(0, sql.ToString());
    }
    protected void FillGirdView(int currentPage, string cmdText)
    {
        if (string.IsNullOrEmpty(cmdText))
        {
            cmdText = ViewState[this.ClientID + "cmdText"].ToString();
        }
        ViewState[this.ClientID + "cmdText"] = cmdText;
        SqlSplitPage splitPage = new SqlSplitPage(base.Connection, cmdText);
        splitPage.PageSize = 10;
        DataSet ds = splitPage.LoadDataSet(currentPage);
        gridView.ShowFooter = true;
        gridView.NavigationData = splitPage.GetNavigationData(currentPage);
        gridView.DataSource = ds.Tables[0];
        gridView.DataBind();
    } 

    protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[2].Text = PMSCodeCategory.GetName(e.Row.Cells[2].Text);
            e.Row.Cells[9].Text = PMSTaskState.GetName(e.Row.Cells[9].Text);
            e.Row.Cells[10].Text = PMSGoodsState.GetName(e.Row.Cells[10].Text);
        }
    }

    protected void gridView_SplitPageIndexChange(object sender, CommandEventArgs e)
    {
        FillGirdView(Int32.Parse(e.CommandArgument.ToString()), ViewState[this.ClientID + "cmdText"].ToString());
    }

    private void ClearValue()
    {
        tbGuest.Text = "";
        tbLocation.Text = "";
        tbPhone.Text = "";
        tbTroubleDescription.Text = "";
        lbUserID.Text = SessionManager.LoginName;
        lbOrgID.Text = SessionManager.OrgName;
        cbIsReqGood.Checked = false;
        lbCreateDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        hfAddOrEdit.Value = "Add";
        hfTaskID.Value = string.Empty;
        pnlGrid.Visible = false;
        pnlEdit.Visible = true;
        ClearValue();
        DataSet ds = PMSAccess.GetDataSet(this.Connection, "select * from " + this.TableName + " where 1=2 ", this.TableName);
        SessionManager.DataSet = ds; 
        TaskPersonItem.ShowWorkTime = false;
        TaskPersonItem.InitData("TaskID", hfTaskID.Value);
    }

    protected void btnEdit_Click(object sender, EventArgs e)
    {
        //任务项目taskItemID
        string taskItemID = Request["TaskID"];
        if (string.IsNullOrEmpty(taskItemID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }

        hfAddOrEdit.Value = "Edit";
        //判断是否已经派发人员
        bool hasDispatch = true;
        string groupCode = string.Empty;
        string taskID = string.Empty;
        //如果已经派发进行修改操作
        DataSet tempds = PMSAccess.GetDataSet("PMS_TaskItem", "TaskItemID", taskItemID);
        if (tempds != null && tempds.Tables.Count > 0 && tempds.Tables[0].Rows.Count > 0)
        { 
            DataRow dr = tempds.Tables[0].Rows[0];
            groupCode = dr["SNGroup"].ToString();
            taskID = dr["TaskID"].ToString();
            if (Convert.ToInt32(dr["TaskState"]) == PMSTaskState.Complete)
            {
                Alert("您选择的任务已经完成，不能再进行操作！");
                return;
            }
        }
        else
        {
            hasDispatch = false;
            //如果还没有派发进行派发操作 taskItemID就是TaskID
            taskID = taskItemID;
        }
        hfHasDispatch.Value = hasDispatch.ToString().ToLower();
        //设置任务主表主键值
        hfTaskID.Value = taskID;
        DataSet ds = PMSAccess.GetDataSet(this.TableName, this.Key, taskID);
         
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
        {
            Alert("您选择的记录已经被删除，请刷新数据！");
            return;
        }
        DataRow row = ds.Tables[this.TableName].Rows[0];
        if (Convert.ToInt32(row["TaskState"]) == PMSTaskState.Complete)
        {
            Alert("您选择的任务已经完成，不能再进行操作！");
            return;
        } 
        pnlGrid.Visible = false;
        pnlEdit.Visible = true;
        ClearValue();

        tabsMenu.SelectedIndex = 0;

        SessionManager.DataSet = ds;
        TaskPersonItem.ShowWorkTime = false;
        TaskPersonItem.InitData("TaskID", taskItemID, string.Empty);
 
        UserAccess user = new UserAccess(base.Connection); 
        tbGuest.Text = row["Guest"].ToString();
        tbLocation.Text = row["Location"].ToString();
        tbPhone.Text = row["Phone"].ToString();
        tbTroubleDescription.Text = row["TroubleDescription"].ToString();
        lbOrgID.Text = user.GetUserOrgName(row["OrgID"].ToString());
        lbUserID.Text = user.GetUserNameByUserID(row["UserID"].ToString());
        cbIsReqGood.Checked = Convert.ToBoolean(row["IsRequestGood"]);
        lbCreateDate.Text = Convert.ToDateTime(row["CreateDate"].ToString()).ToString("yyyy-MM-dd HH:mm"); 
    } 
    protected void btnRemove_Click(object sender, EventArgs e)
    {
        //任务项目taskItemID
        string taskItemID = Request["TaskID"];
        if (string.IsNullOrEmpty(taskItemID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        } 
        //判断是否已经派发人员
        bool hasDispatch = true; 
        string taskID = string.Empty;
        //如果已经派发进行修改操作
        DataSet tempds = PMSAccess.GetDataSet("PMS_TaskItem", "TaskItemID", taskItemID);
        if (tempds != null && tempds.Tables.Count > 0 && tempds.Tables[0].Rows.Count > 0)
        {
            DataRow dr = tempds.Tables[0].Rows[0]; 
            taskID = dr["TaskID"].ToString();
            if (Convert.ToInt32(dr["TaskState"]) == PMSTaskState.Complete)
            {
                Alert("您选择的任务已经完成，不能再进行操作！");
                return;
            }
        }
        else
        {
            hasDispatch = false;
            //如果还没有派发进行派发操作 taskItemID就是TaskID
            taskID = taskItemID;
        }

        string cmdText = "";
        if (hasDispatch)
        {
            cmdText = @"delete from PMS_TaskItem where TaskItemID='{0}';
                        delete from PMS_TaskUser where TaskID='{0}';
                        delete from IC_RequisitionItem where RequisitionID in (select RequisitionID from IC_Requisition where TaskID='{0}');
                        delete from IC_Requisition where TaskID='{0}';";
            cmdText = string.Format(cmdText, taskItemID);
        }
        else
        {
            cmdText = @"delete from PMS_TaskLX where TaskID='{0}';";
            cmdText = string.Format(cmdText, taskID);
        }
        
        BaseAccess.ExecuteNonQuery(base.Connection, cmdText);
        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
    }
    protected void btnListDocument_Click(object sender, EventArgs e)
    {
        //任务项目taskItemID
        string taskItemID = Request["TaskID"];
        if (string.IsNullOrEmpty(taskItemID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        } 
        string filePath = Server.MapPath(SessionManager.TempVirtualFolder + System.Guid.NewGuid().ToString()+".doc");
        string outinfo = DocumentHelper.ExportDispatchDocument(PMSConst.PMSDispatchDocTemplatePath, filePath, taskItemID);
        if (string.IsNullOrEmpty(outinfo))
        {
            base.DownLoadFile(filePath, "派工单.doc");
        }
        else
        {
            tipMessage1.ShowMessage(outinfo, 5000); 
        }
    }
    
    protected void btnDocument_Click(object sender, EventArgs e)
    {
        string taskID = hfTaskID.Value; 
        string filePath = Server.MapPath(SessionManager.TempVirtualFolder + System.Guid.NewGuid().ToString()+".doc");
        string outinfo = DocumentHelper.ExportDispatchDocument(PMSConst.PMSDispatchDocTemplatePath, filePath, taskID);
        if (string.IsNullOrEmpty(outinfo))
        {
            base.DownLoadFile(filePath, "派工单.doc");
        }
        else
        {
            tipMessage1.ShowMessage(outinfo, 5000); 
        }
    }

    

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (hfAddOrEdit.Value == "Add")
        {

            //判断是否选择派修人员
            string result = TaskPersonItem.PreProcessSave(); 
            string taskId = System.Guid.NewGuid().ToString();
            hfTaskID.Value = taskId; 
            //添加任务
            DataRow row = SessionManager.DataSet.Tables[this.TableName].NewRow();
            row["TaskID"] = taskId;
            //row["TaskCode"] =
            row["Guest"] = tbGuest.Text.Trim();
            row["Location"] = tbLocation.Text.Trim();
            row["Phone"] = tbPhone.Text.Trim();
            row["TroubleDescription"] = tbTroubleDescription.Text.Trim();
            row["UserID"] = SessionManager.UserID;
            row["OrgID"] = SessionManager.OrgID;
            row["CreateDate"] = DateTime.Now.ToString();
            row["GoodsState"] = PMSGoodsState.NotOut;
            row["TaskState"] = PMSTaskState.Running;
            row["SourceState"] = PMSSourceState.From123;
            row["IsRequestGood"] = cbIsReqGood.Checked;
            SessionManager.DataSet.Tables[this.TableName].Rows.Add(row);
            PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select * from PMS_TaskItem where TaskID='" + hfTaskID.Value + "' ", "PMS_TaskItem");
            PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select * from IC_Requisition where 1=2 ", "IC_Requisition");

            if (SessionManager.DataSet.Tables.Contains(TaskPersonItem.m_TableName))
            { 
                DataTable dt = SessionManager.DataSet.Tables[TaskPersonItem.m_TableName];
                if(dt!=null && dt.Rows.Count>0)
                    row["TaskState"] = PMSTaskState.Dispatch;
                List<string> list = new List<string>();
                DataRow itemrow = null;
                string taskItemId = null;
                foreach (DataRow dr in dt.Rows)
                {  
                    if (!list.Contains(dr["GroupCode"].ToString()))
                    {
                        list.Add(dr["GroupCode"].ToString());
                        taskItemId = System.Guid.NewGuid().ToString();
                        itemrow = SessionManager.DataSet.Tables["PMS_TaskItem"].NewRow();
                        itemrow["TaskItemID"] = taskItemId;
                        itemrow["TaskID"] = taskId;
                        itemrow["SNYear"] = DateTime.Now.ToString("yyyy");
                        itemrow["SNGroup"] = dr["GroupCode"];
                        itemrow["SNTask"] = PMSCodeCategory.PMS_RCLX;
                        itemrow["SNProject"] = "01";
                        itemrow["SNDispatch"] = DocumentHelper.Instance.GetDispatchCode(itemrow["SNYear"].ToString(), dr["GroupCode"].ToString(), PMSCodeCategory.PMS_RCLX, "01");
                        itemrow["TaskState"] = PMSTaskState.Dispatch;
                        itemrow["TaskCode"] = itemrow["SNYear"].ToString() + itemrow["SNGroup"].ToString() + itemrow["SNTask"].ToString() + itemrow["SNProject"].ToString() + itemrow["SNDispatch"].ToString();
                        PMSAccess.AppendValue(ref itemrow, EnumOperator.ADD);
                        SessionManager.DataSet.Tables["PMS_TaskItem"].Rows.Add(itemrow);
                        if (cbIsReqGood.Checked)
                        {
                            string guid = System.Guid.NewGuid().ToString();
                            DataRow req_dr = SessionManager.DataSet.Tables["IC_Requisition"].NewRow();
                            req_dr["RequisitionID"] = guid;
                            req_dr["TaskID"] = taskItemId;
                            req_dr["Status"] = PMSGoodsState.NotOut;
                            req_dr["RequisitionType"] = PMSCodeCategory.PMS_CKLX_LingLiao;
                            req_dr["RequisitionCode"] = PMSAccess.GetCode(EnumCodeKind.LingLiao);
                            req_dr["RequisitionUser"] = SessionManager.Username;
                            req_dr["RequisitionDate"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            PMSAccess.AppendValue(ref req_dr, EnumOperator.ADD);
                            SessionManager.DataSet.Tables["IC_Requisition"].Rows.Add(req_dr);
                        }
                    }
                    dr["TaskID"] = itemrow["TaskItemID"];
                    dr["OrgID"] = SessionManager.OrgID;
                    dr["CreateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                    dr["CreateUser"] = SessionManager.LoginName;
                }
            }

            PMSAccess.UpdateDataSet(this.Connection, new string[] { this.TableName, "PMS_TaskUser", "PMS_TaskItem", "IC_Requisition" }, SessionManager.DataSet);
            tipMessage1.ShowMessage("保存成功", 5000); 
        }
        else if (hfAddOrEdit.Value == "Edit")
        {

            //判断是否选择派修人员
            string result = TaskPersonItem.PreProcessSave();
            string taskId = hfTaskID.Value;
            //添加任务
            DataRow row = SessionManager.DataSet.Tables[this.TableName].Rows[0];
            row["TaskID"] = taskId;
            row["Guest"] = tbGuest.Text.Trim();
            row["Location"] = tbLocation.Text.Trim();
            row["Phone"] = tbPhone.Text.Trim();
            row["TroubleDescription"] = tbTroubleDescription.Text.Trim();
            row["UserID"] = SessionManager.UserID;
            row["OrgID"] = SessionManager.OrgID;
            row["IsRequestGood"] = cbIsReqGood.Checked;
            PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select * from PMS_TaskItem where 1=2 ", "PMS_TaskItem");
            PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select * from IC_Requisition where 1=2 ", "IC_Requisition");
            if (SessionManager.DataSet.Tables.Contains(TaskPersonItem.m_TableName))
            {
                PMSAccess.ExecuteNonQuery(this.Connection,"delete from PMS_TaskItem where TaskID='" + hfTaskID.Value + "';");
                DataTable dt = SessionManager.DataSet.Tables[TaskPersonItem.m_TableName];
                if (dt != null && dt.Rows.Count > 0)
                    row["TaskState"] = PMSTaskState.Dispatch;
                List<string> list = new List<string>();
                DataRow itemrow = null;
                string taskItemId = System.Guid.NewGuid().ToString();
                foreach (DataRow dr in dt.Rows)
                {  
                    if (!list.Contains(dr["GroupCode"].ToString()))
                    {
                        list.Add(dr["GroupCode"].ToString());
                        taskItemId = System.Guid.NewGuid().ToString();
                        itemrow = SessionManager.DataSet.Tables["PMS_TaskItem"].NewRow(); 
                        itemrow["TaskItemID"] = taskItemId;
                        itemrow["TaskID"] = hfTaskID.Value;
                        itemrow["SNYear"] = DateTime.Now.ToString("yyyy");
                        itemrow["SNGroup"] = dr["GroupCode"];
                        itemrow["SNTask"] = PMSCodeCategory.PMS_RCLX;
                        itemrow["SNProject"] = "01";
                        itemrow["SNDispatch"] = DocumentHelper.Instance.GetDispatchCode(itemrow["SNYear"].ToString(), dr["GroupCode"].ToString(), PMSCodeCategory.PMS_RCLX, "01");
                        itemrow["TaskState"] = PMSTaskState.Dispatch;
                        itemrow["TaskCode"] = itemrow["SNYear"].ToString() + itemrow["SNGroup"].ToString() + itemrow["SNTask"].ToString() + itemrow["SNProject"].ToString() + itemrow["SNDispatch"].ToString();
                        PMSAccess.AppendValue(ref itemrow, EnumOperator.ADD);
                        SessionManager.DataSet.Tables["PMS_TaskItem"].Rows.Add(itemrow);
                        if (cbIsReqGood.Checked&&hfHasDispatch.Value =="false")
                        {
                            string guid = System.Guid.NewGuid().ToString();
                            DataRow req_dr = SessionManager.DataSet.Tables["IC_Requisition"].NewRow();
                            req_dr["RequisitionID"] = guid;
                            req_dr["TaskID"] = taskItemId;
                            req_dr["Status"] = PMSGoodsState.NotOut;
                            req_dr["RequisitionType"] = PMSCodeCategory.PMS_CKLX_LingLiao;
                            req_dr["RequisitionCode"] = PMSAccess.GetCode(EnumCodeKind.LingLiao);
                            req_dr["RequisitionUser"] = SessionManager.Username;
                            req_dr["RequisitionDate"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            PMSAccess.AppendValue(ref req_dr, EnumOperator.ADD);
                            SessionManager.DataSet.Tables["IC_Requisition"].Rows.Add(req_dr);
                        }
                    }
                    dr["TaskID"] = itemrow["TaskItemID"];
                    dr["OrgID"] = SessionManager.OrgID;
                    dr["CreateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                    dr["CreateUser"] = SessionManager.LoginName;
                }
            }

            PMSAccess.UpdateDataSet(this.Connection, new string[] { this.TableName, "PMS_TaskUser", "PMS_TaskItem", "IC_Requisition" }, SessionManager.DataSet);
            tipMessage1.ShowMessage("保存成功", 5000);
        } 
    }

    protected void btnPreTabsMenu_Click(object sender, EventArgs e)
    {

    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        pnlGrid.Visible = true;
        pnlEdit.Visible = false;
        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
    }

    protected void btnSelect_Click(object sender, EventArgs e)
    {
        if (tabsMenu.SelectedIndex == 1)
        {
            if (TaskPersonItem.OnSelect != null)
                TaskPersonItem.OnSelect(sender, e); 
        } 
    } 
}
